<template>
  <div class="inventory">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="物料编码">
          <el-input v-model="searchForm.materialCode" placeholder="请输入物料编码" clearable />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.materialName" placeholder="请输入物料名称" clearable />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable>
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="searchForm.stockStatus" placeholder="请选择状态" clearable>
            <el-option label="充足" value="sufficient" />
            <el-option label="不足" value="insufficient" />
            <el-option label="缺货" value="out_of_stock" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="handleAdjust" v-if="hasPermission('warehouse:inventory:edit')">
        <el-icon><Edit /></el-icon>库存调整
      </el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
      <el-button type="warning" @click="handleStockCheck">盘点</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="card">
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="materialCode" label="物料编码" width="120" />
        <el-table-column prop="materialName" label="物料名称" width="200" />
        <el-table-column prop="specification" label="规格型号" width="150" />
        <el-table-column prop="warehouseName" label="仓库" width="120" />
        <el-table-column prop="location" label="库位" width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="quantity" label="当前库存" width="120">
          <template #default="{ row }">
            <span :class="getStockClass(row.stockStatus)">{{ row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="120" />
        <el-table-column prop="maxStock" label="最高库存" width="120" />
        <el-table-column prop="stockStatus" label="库存状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStockStatusType(row.stockStatus)">
              {{ getStockStatusText(row.stockStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdateTime" label="最后更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleAdjust(row)"
              v-if="hasPermission('warehouse:inventory:edit')"
            >
              调整
            </el-button>
            <el-button type="info" size="small" @click="handleHistory(row)">历史</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 库存调整对话框 -->
    <el-dialog
      v-model="adjustDialogVisible"
      title="库存调整"
      width="500px"
      @close="handleAdjustDialogClose"
    >
      <el-form
        ref="adjustFormRef"
        :model="adjustForm"
        :rules="adjustFormRules"
        label-width="100px"
      >
        <el-form-item label="物料名称">
          <el-input v-model="adjustForm.materialName" disabled />
        </el-form-item>
        
        <el-form-item label="当前库存">
          <el-input v-model="adjustForm.currentQuantity" disabled />
        </el-form-item>
        
        <el-form-item label="调整类型" prop="adjustType">
          <el-radio-group v-model="adjustForm.adjustType">
            <el-radio value="increase">增加</el-radio>
            <el-radio value="decrease">减少</el-radio>
            <el-radio value="set">设置</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="调整数量" prop="adjustQuantity">
          <el-input-number 
            v-model="adjustForm.adjustQuantity" 
            :min="0" 
            :precision="2" 
            style="width: 100%"
            placeholder="请输入调整数量"
          />
        </el-form-item>
        
        <el-form-item label="调整原因" prop="reason">
          <el-select v-model="adjustForm.reason" placeholder="请选择调整原因" style="width: 100%">
            <el-option label="盘点调整" value="stock_check" />
            <el-option label="报损调整" value="damage" />
            <el-option label="系统调整" value="system" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="adjustForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="adjustDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdjustSubmit" :loading="adjustSubmitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 搜索表单
const searchForm = reactive({
  materialCode: '',
  materialName: '',
  warehouseId: '',
  stockStatus: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 仓库数据
const warehouses = ref([
  { id: 1, name: '主仓库' },
  { id: 2, name: '原料仓库' },
  { id: 3, name: '成品仓库' }
])

// 库存调整对话框相关
const adjustDialogVisible = ref(false)
const adjustSubmitLoading = ref(false)
const adjustFormRef = ref()

// 库存调整表单
const adjustForm = reactive({
  materialId: null,
  materialName: '',
  currentQuantity: 0,
  adjustType: 'increase',
  adjustQuantity: 0,
  reason: '',
  remark: ''
})

// 库存调整表单验证规则
const adjustFormRules = {
  adjustType: [{ required: true, message: '请选择调整类型', trigger: 'change' }],
  adjustQuantity: [{ required: true, message: '请输入调整数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请选择调整原因', trigger: 'change' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    materialCode: 'M001',
    materialName: '原材料A',
    specification: '规格A',
    warehouseName: '主仓库',
    location: 'A-01-01',
    unit: 'kg',
    quantity: 1000,
    minStock: 100,
    maxStock: 2000,
    stockStatus: 'sufficient',
    lastUpdateTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    materialCode: 'M002',
    materialName: '半成品B',
    specification: '规格B',
    warehouseName: '主仓库',
    location: 'A-02-01',
    unit: '件',
    quantity: 50,
    minStock: 100,
    maxStock: 500,
    stockStatus: 'insufficient',
    lastUpdateTime: '2024-01-14 14:20:00'
  },
  {
    id: 3,
    materialCode: 'M003',
    materialName: '成品C',
    specification: '规格C',
    warehouseName: '成品仓库',
    location: 'B-01-01',
    unit: '套',
    quantity: 0,
    minStock: 50,
    maxStock: 200,
    stockStatus: 'out_of_stock',
    lastUpdateTime: '2024-01-13 09:15:00'
  },
  {
    id: 4,
    materialCode: 'M004',
    materialName: '包装盒',
    specification: '标准包装',
    warehouseName: '主仓库',
    location: 'A-03-01',
    unit: '个',
    quantity: 2000,
    minStock: 500,
    maxStock: 5000,
    stockStatus: 'sufficient',
    lastUpdateTime: '2024-01-12 16:45:00'
  },
  {
    id: 5,
    materialCode: 'M005',
    materialName: '电子元件',
    specification: 'IC芯片',
    warehouseName: '主仓库',
    location: 'A-04-01',
    unit: '片',
    quantity: 800,
    minStock: 200,
    maxStock: 1000,
    stockStatus: 'sufficient',
    lastUpdateTime: '2024-01-11 11:20:00'
  },
  {
    id: 6,
    materialCode: 'M006',
    materialName: '机械零件',
    specification: '轴承',
    warehouseName: '主仓库',
    location: 'A-05-01',
    unit: '个',
    quantity: 1200,
    minStock: 300,
    maxStock: 1500,
    stockStatus: 'sufficient',
    lastUpdateTime: '2024-01-10 09:30:00'
  },
  {
    id: 7,
    materialCode: 'M007',
    materialName: '化工原料',
    specification: '树脂',
    warehouseName: '主仓库',
    location: 'A-06-01',
    unit: 'kg',
    quantity: 1500,
    minStock: 500,
    maxStock: 2000,
    stockStatus: 'sufficient',
    lastUpdateTime: '2024-01-09 14:15:00'
  },
  {
    id: 8,
    materialCode: 'M008',
    materialName: '软件授权',
    specification: '企业版',
    warehouseName: '成品仓库',
    location: 'B-02-01',
    unit: '套',
    quantity: 50,
    minStock: 20,
    maxStock: 100,
    stockStatus: 'sufficient',
    lastUpdateTime: '2024-01-08 10:45:00'
  }
]

// 获取库存状态类型
const getStockStatusType = (status) => {
  const statusMap = {
    sufficient: 'success',
    insufficient: 'warning',
    out_of_stock: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取库存状态文本
const getStockStatusText = (status) => {
  const statusMap = {
    sufficient: '充足',
    insufficient: '不足',
    out_of_stock: '缺货'
  }
  return statusMap[status] || '未知'
}

// 获取库存样式类
const getStockClass = (status) => {
  const classMap = {
    sufficient: 'stock-sufficient',
    insufficient: 'stock-insufficient',
    out_of_stock: 'stock-out'
  }
  return classMap[status] || ''
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    materialCode: '',
    materialName: '',
    warehouseId: '',
    stockStatus: ''
  })
  handleSearch()
}

// 加载数据
const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看功能开发中...')
}

// 库存调整
const handleAdjust = (row) => {
  Object.assign(adjustForm, {
    materialId: row.id,
    materialName: row.materialName,
    currentQuantity: row.quantity,
    adjustType: 'increase',
    adjustQuantity: 0,
    reason: '',
    remark: ''
  })
  adjustDialogVisible.value = true
}

// 提交库存调整
const handleAdjustSubmit = async () => {
  try {
    await adjustFormRef.value.validate()
    adjustSubmitLoading.value = true
    
    // 模拟提交
    setTimeout(() => {
      ElMessage.success('库存调整成功')
      adjustDialogVisible.value = false
      loadData()
      adjustSubmitLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 库存调整对话框关闭
const handleAdjustDialogClose = () => {
  Object.assign(adjustForm, {
    materialId: null,
    materialName: '',
    currentQuantity: 0,
    adjustType: 'increase',
    adjustQuantity: 0,
    reason: '',
    remark: ''
  })
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 盘点
const handleStockCheck = () => {
  ElMessage.info('盘点功能开发中...')
}

// 历史记录
const handleHistory = (row) => {
  ElMessage.info('历史记录功能开发中...')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.inventory {
  .stock-sufficient {
    color: $success-color;
    font-weight: bold;
  }
  
  .stock-insufficient {
    color: $warning-color;
    font-weight: bold;
  }
  
  .stock-out {
    color: $danger-color;
    font-weight: bold;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 